package com.vpen.iot.manager;

import cn.hutool.core.util.ObjectUtil;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;

import java.net.SocketAddress;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Vpen
 * @date 2023/7/8 11:46
 */
@Slf4j
public class LinkManager {
    /**
     * 接入码做key,值是他的所有信息
     */
    private static final Map<String, LinkInfo> LINK_MAP = new ConcurrentHashMap<>(16);

    /**
     * 冗余一个从链路的map，加快查找速度，key是地址，值是指向LINK_MAP的值
     */
    private static final Map<SocketAddress, LinkInfo> ADDRESS_MAP = new ConcurrentHashMap<>(16);


    public static LinkInfo addChannel(String key, Channel channel) {
        LinkInfo linkInfo = getLinkInfo(key);
        linkInfo.setChannel(channel);
        linkInfo.setKey(key);
        ADDRESS_MAP.putIfAbsent(channel.remoteAddress(), linkInfo);
        return linkInfo;
    }


    public static LinkInfo getLinkInfo(String key) {
        LinkInfo linkInfo = LINK_MAP.get(key);
        if (ObjectUtil.isNull(linkInfo)) {
            linkInfo = new LinkInfo().setKey(key);
            LINK_MAP.put(key, linkInfo);
        }
        return linkInfo;
    }


    public static LinkInfo getLinkInfo(SocketAddress address) {
        LinkInfo linkInfo = ADDRESS_MAP.get(address);
        if (ObjectUtil.isNull(linkInfo)) {
            log.debug("通过地址找不到连接信息");
        }
        return linkInfo;
    }

    public static LinkInfo removeChannel(SocketAddress socketAddress) {
        LinkInfo linkInfo = getLinkInfo(socketAddress);
        if (ObjectUtil.isNotNull(linkInfo)) {
            LINK_MAP.remove(linkInfo.getKey());
        }
        ADDRESS_MAP.remove(socketAddress);
        return linkInfo;
    }
}
